#include "mytcpsocket.h"
#include <QDebug>

MyTcpSocket::MyTcpSocket(QObject *parent)
    : QObject(parent)
{

}

void MyTcpSocket::doConnect()
{
    socket = new QTcpSocket(this);
    connect(socket, SIGNAL(connected()), this, SLOT(connected()));
    connect(socket, SIGNAL(disconnected()), this, SLOT(disconnected()));
    connect(socket, SIGNAL(readyRead()), this, SLOT(readyRead()));
    connect(socket, SIGNAL(bytesWritten(qint64)), this, SLOT(bytesWritten(qint64)));

    qDebug() << "Connecting ...";
    // this is not blocking call
    socket->connectToHost("baidu.com", 80);

    if (!socket->waitForConnected(5000)){
        qDebug() << "Connect error: " << socket->errorString();
    }

}

void MyTcpSocket::readyRead()
{
    qDebug() << "Reading ...";
    qDebug() << socket->readAll();
}

void MyTcpSocket::connected()
{
    qDebug() << "Connected.";
    socket->write("HEAD / HTTP/1.0\r\n\r\n\r\n\r\n");
}

void MyTcpSocket::disconnected()
{
    qDebug() << "Disconnected.";
}

void MyTcpSocket::bytesWritten(qint64 bytes)
{
    qDebug() << bytes << " bytes written.";
}
